package readtreefromfile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReadTreeFromFile extends TreeParser {

	public ReadTreeFromFile(String path) {
		this.retrieveData = new ReadFromTxtFile(path);
		this.parseCategory = new ParseSpaceIndentCategory();
	}

	public Category process() throws Exception {
		List<String> eachLine = this.getData();
		Map<Integer, Category> treeLevel = new HashMap<Integer, Category>();
		Category root = this.parseCat(eachLine.get(0));
		if (root != null) {
			treeLevel.put(root.getLevel(), root);
			for (int i = 1; i < eachLine.size(); i++) {
				String tmp = eachLine.get(i);
				Category cat = parseCat(tmp);
				if (cat != null) {
					treeLevel.put(cat.getLevel(), cat);
					if (cat.getLevel() > 0) {
						// this isn't root category
						Category parent = treeLevel.get(cat.getLevel() - 1);
						parent.addChildren(cat);
					}
				}
			}
		}
		return root;
	}

	public static void main(String[] args) {
		String filePath="D:\\tmp_download\\tree.txt";
		ReadTreeFromFile read = new ReadTreeFromFile(filePath);
		try {
			Category result = read.process();
			if (result != null) {
				read.output(result);
			} else {
				System.out.println("Empty tree.");
			}
		} catch (FileNotFoundException e) {
			System.out.println("Can't find file:"+filePath);
		} catch (IOException e) {
			System.out.println("Encounter IO issue:"+e);
		} catch (Exception e) {
			System.out.println("Encounter issue:"+e);
		}
	}
}
